/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package security;

import constants.Consts;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Bari
 */
public class KeyKeeper {

    private static KeyKeeper instance;
    
    private  PublicKey publicKey;
    private  PrivateKey privateKey;
    
    private static KeyKeeper GetInstance()
    {
        if (instance == null) {
            instance = new KeyKeeper();
        }
        return instance;
    }

    public static PublicKey GetPublicKey() {
        return GetInstance().publicKey;
    }

    public static PrivateKey GetPrivateKey() {
        return GetInstance().privateKey;
    }

    public KeyKeeper() {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = readPrivateKey(keyFactory);
            publicKey = readPublicKey(keyFactory);
        } catch (IOException ex) {
            Logger.getLogger(KeyKeeper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (GeneralSecurityException ex) {
            Logger.getLogger(KeyKeeper.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private PrivateKey readPrivateKey(KeyFactory keyFactory) throws IOException, GeneralSecurityException {
        PKCS8EncodedKeySpec keySpecs = new PKCS8EncodedKeySpec(readKeySpecsFromFile(Consts.PATH_PRIVATE_KEY));
        PrivateKey returnKey = keyFactory.generatePrivate(keySpecs);
        return returnKey;
    }

    private PublicKey readPublicKey(KeyFactory keyFactory) throws InvalidKeySpecException, IOException {
        X509EncodedKeySpec keySpecs = new X509EncodedKeySpec(readKeySpecsFromFile(Consts.PATH_PUBLIC_KEY));
        PublicKey returnKey = keyFactory.generatePublic(keySpecs);
        return returnKey;
    }

    private byte[] readKeySpecsFromFile(String filename)
            throws IOException {

        InputStream inStream = getClass().getClassLoader().getResourceAsStream(filename);

        DataInputStream dataIn = new DataInputStream(inStream);
        byte[] key = new byte[(int) inStream.available()];
        dataIn.readFully(key);
        dataIn.close();
        return key;
    }
}
